/*
 * @Author: mikey.zhaopeng
 * @Date:   2016-05-25 19:42:27
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:16:18
 */

'use strict';
define([
    '../../../framework/base/baseView',
    'text!../tpl/step1.html',
    'text!../tpl/step1Filter.html',
    'text!../tpl/step1AdTargetFilter.html',
    'text!../tpl/step1FilterChrild.html',
    'text!../tpl/step1AdTargetFilterChrild.html',
    'text!../tpl/step1CreativeType.html',
    '../../../framework/bean/ec',
    '../../../framework/bean/feed',
    '../../../framework/bean/ecMaterielCategory'
], function(
    BaseView,
    tpl,
    filterTpl,
    adTargetFilter,
    chrildTpl,
    adTargetChrildTpl,
    creativeTypeTpl,
    ecBean,
    feedBean,
    ecMaterielCategoryBean
) {
    function me() {
        BaseView.apply(this, arguments);
        var self = this;
        /**
         * [init description]
         * @param  {[type]} $root    [description]
         * @param  {[type]} jumpStep [description]
         * @param  {[type]} restore  [是否从缓存恢复]
         * @return {[type]}          [description]
         */
        this.init = function($root, jumpStep, restore) {
            jumpStep(1);
            self.moduleKey = 'createMaterialStep1'; //模块缓存 module 名称
            self.$root = $root;
            self.restore = restore;
            self.$root.html(I18N.parse(tpl,'createMaterial'));
            self.$product = self.$root.find('.ndp-drop-wrapper[name=product]');
            self.$feed = self.$root.find('.ndp-drop-wrapper[name=feed]');
            self.$filters = self.$root.find('.filters[name=filters]');
            self.render();
        }

        this.render = function() {
            self.renderProduct();
            self.rendersupportCreate();
            self.event();
        }


        this.event = function() {
            self.$root.find('.btn-next').off('click').on('click', $.proxy(self.submitStep1, self));
            self.$product.off("ITEM_CLICK").on('ITEM_CLICK', $.proxy(self.renderFeed, self));
            self.$feed.off("ITEM_CLICK").on('ITEM_CLICK', $.proxy(self.chooseFeed, self));
            self.$root.off('click', '.filters .filter-child .expond-more').on('click', '.filters .filter-child .expond-more', $.proxy(self.expondMoreFilter, self));
            self.$root.off('click', '.filters .filter-child input[type]').on('click', '.filters .filter-child input[type]', $.proxy(self.filterClick, self));

            //self.$root.off('click', '[data-filter-categorytype="adTarget"] .filter-child').on('click', '[data-filter-categorytype="adTarget"] .filter-child', $.proxy(self.adTargetClick, self));
        }

        this.renderProduct = function() {
            ecBean.allWebSiteByUserId(function(results) {
                var appsData = [];
                $.each(results, function(i, obj) {
                    var tempObj = {};
                    tempObj.id = obj.productManageProductId;
                    tempObj.val = obj.productManageProductId;
                    tempObj.pageId = obj.pageId;
                    tempObj.text = obj.companyName;
                    appsData.push(tempObj);
                });
                var prodTip = {
                    val: 0,
                    text: self.i18n('pleaseSelectProduct')
                };
                var triggerFlag = false;
                if (self.restore) {
                    var prodId = self.kit.getCache(self.moduleKey, 'prodId');
                    if (prodId) {
                        var tmpObj = _.findWhere(appsData, {
                            id: prodId
                        });
                        if (tmpObj) {
                            prodTip = tmpObj;
                            prodTip.customTigger = true; //标记是自定义的 tigger
                            triggerFlag = true;
                        }
                    }
                }
                self.$product.empty().drop({
                    data: appsData,
                    name: "product"
                }).val(prodTip);

                self.$feed.empty().drop({
                    data: [],
                    name: "feed"
                }).val({
                    val: 0,
                    text: self.i18n('pleaseSelectFeed')
                });
                if (triggerFlag) {
                    fireEvent(self.$product.get(0), "ITEM_CLICK", prodTip);
                }
            });
        }



        this.renderFeed = function(e) {
            var prodId = e.originalEvent.data.val;
            var customTigger = e.originalEvent.data.customTigger; //如果不是自定义的 trigger,那么就需要清空缓存
            var params = {
                prodId: prodId
            }
            self.kit.setCache(self.moduleKey, 'prodId', prodId);
            feedBean.findByProd(params, function(results) {
                $.each(results, function(i, obj) {
                    obj.text = obj.feedName;
                });
                var feedTip = {
                    val: 0,
                    text: self.i18n('pleaseSelectFeed')
                };
                var triggerFlag = false;
                if (self.restore && customTigger) {
                    var feedId = self.kit.getCache(self.moduleKey, 'feedId');
                    if (feedId) {
                        var tmpObj = _.findWhere(results, {
                            id: feedId * 1
                        });
                        if (tmpObj) {
                            feedTip = tmpObj;
                            feedTip.val = feedId;
                            triggerFlag = true;
                        }
                    }
                }
                self.$feed.empty().drop({
                    data: results,
                    name: "feed"
                }).val(feedTip);
                fireEvent(self.$feed.get(0), "ITEM_CLICK", feedTip);
            });
        }

        /**
         * [rendersupportCreate 渲染查询条件]
         * @return {[type]} [description]
         */
        this.rendersupportCreate = function() {
            ecMaterielCategoryBean.supportCreate(function(results) {
                console.info(results)
                self.$filters.empty();
                _.each(results, function(el) {
                    self.$filters.append(self.getFilterHtml(el));
                });

                if (self.restore) {
                    var options = self.kit.getCache(self.moduleKey, 'options');
                    console.log(options)
                    if (options) {
                        self.$root.find('.filters div[data-filter-categoryType]').each(function(index, el) {
                            var categoryType = $(this).attr('data-filter-categoryType');
                            var optionsType = options[categoryType];
                            if (optionsType) {
                                $(this).find('.filter-child input[type]').each(function(index, el) {
                                    var that = this;
                                    var id = $(that).attr('data-id');
                                    _.each(optionsType, function(option) {
                                        if (option.id == id) {
                                            $(that).prop('checked', option.checked);
                                        }
                                    });

                                });
                            }
                        });
                    }
                }
            });
        }



        /**
         * [getFilterHtml 获取到 filter 的 html]
         * @param  {[type]} el  [description]
         * @param  {[type]} sub [是否第三级需要展开的标记]
         * @return {[type]}     [description]
         */
        this.getFilterHtml = function(el, sub) {
            if (el.categoryType == 'creativeType') {
                return self.getCreativeTypeHtml(el);
            }
            var chHtml = ''; //第二级的 html
            var subHtmlArr = []; // 第三级需要展开的 html
            _.each(el.children, function(ch) {
                if (ch.children.length > 0) { //是否出现下拉箭头
                    ch.title = ch.categoryName + '<span class="expond-more" style="color:#fd9611;cursor: pointer;" href="javascript:void(0)">[ detail <span class="sort-down glyphicon glyphicon-chevron-down"></span> ]</span>';
                    ch.triangle = '<div class="triangle-up" style="display: block;" data-expond-id="' + ch.id + '"></div>';
                    var subHtml = self.getFilterHtml(ch, 'sub'); //调用生成第三级需要展开的 html
                    subHtmlArr.push(subHtml);
                } else {
                    ch.title = ch.categoryName;
                    ch.triangle = '';
                }
                if (sub && sub == 'sub') { //第三级需要展开的 html的结构和第一级一样，但是需要将 categoryName 置为 空
                    el.categoryName = '';
                }
                var tpl2 = (el.categoryType == 'adTarget' || el.categoryType == 'festival') ? adTargetChrildTpl : chrildTpl;
                if (el.categoryType == 'adTarget' || el.categoryType == 'festival') {
                    ch.categoryType = el.categoryType;
                }
                var tmpHtml = _.template(tpl2)({
                    d: ch
                });
                chHtml = chHtml + tmpHtml;
            });
            el.chHtml = chHtml;
            if (sub && sub == 'sub') { // 将第三级需要展开的 html 隐藏
                el.sub = 'more-filter';
                el.display = 'style="display: block;"';
                el.subMore = ' create-aim-wrapper-more';
            } else {
                el.subMore = '';
            }
            var tpl1 = el.categoryType == 'adTarget' ? adTargetFilter : filterTpl;
            var html = _.template(tpl1)({
                d: el
            });
            if (subHtmlArr.length > 0) {
                _.each(subHtmlArr, function(sub) {
                    html = html + sub;
                });
            }
            return html;
        }

        /**
         * [expondMoreFilter 展开下拉]
         * @param  {[type]} e [description]
         * @return {[type]}   [description]
         */
        this.expondMoreFilter = function(e) {
            var id = $(e.currentTarget).parent().data('expond-id');
            self.$root.find('div.triangle-up[data-expond-id!="' + id + '"]').slideUp(); //收起所有
            self.$root.find('div.more-filter[data-expond-id!="' + id + '"]').slideUp(); //收起所有
            self.$root.find('div.triangle-up[data-expond-id="' + id + '"]').slideToggle();
            self.$root.find('div.more-filter[data-expond-id="' + id + '"]').slideToggle(400, function() {
                $(this).css('overflow', '');
            });
        }


        this.filterClick = function(e) {
            var cType = $(e.currentTarget).attr('data-categorytype');
            var id = $(e.currentTarget).attr('id');
            if (cType == 'adTarget') {
                if ($(e.currentTarget).parent().find('.triangle-up')[0]) {
                    self.$root.find('.filters div[data-filter-categoryType=festival] .filter-child input:first').prop('checked', true);
                } else {
                    self.$root.find('.filters div[data-filter-categoryType=festival] .filter-child input').prop('checked', false);
                }
            }

            if (cType == 'festival') {
                var parentId = $(e.currentTarget).closest('.more-filter').attr('data-expond-id');
                self.$root.find('[data-filter-categorytype="adTarget"] input[id="checkbox-' + parentId + '"]').prop('checked', true);
                self.$root.find('[data-filter-categorytype="adTarget"] input[id!="checkbox-' + parentId + '"]').prop('checked', false);
            }
            var options = {}; //
            self.$root.find('.filters div[data-filter-categoryType]').each(function(index, el) {
                var categoryType = $(this).attr('data-filter-categoryType');
                options[categoryType] = [];
                $(this).find('.filter-child input[type]').each(function(index, el) {
                    var option = {};
                    option.id = $(this).attr('data-id');
                    option.pid = $(this).attr('data-pid');
                    option.title = $(this).attr('data-title');
                    option.checked = $(this).prop('checked');
                    option.categoryType = $(this).attr('data-categoryType');
                    options[categoryType].push(option);
                });
            });
            self.kit.setCache(self.moduleKey, 'options', options);
        }

        /**
         * [getCreativeTypeHtml 获取创意类别的html]
         * @param  {[type]} ch [description]
         * @return {[type]}    [description]
         */
        this.getCreativeTypeHtml = function(ch) {
            var tmpHtml = _.template(creativeTypeTpl)({
                d: ch
            });
            return tmpHtml;
        }


        this.chooseFeed = function(e) {
            var feedId = e.originalEvent.data.val;
            self.kit.setCache(self.moduleKey, 'feedId', feedId);
        }

        this.submitStep1 = function(e) {
            var valicateFLag = true; //验证数据是否完整
            var prodId = self.kit.getCache(self.moduleKey, 'prodId');
            if (self.kit.isBlank(prodId)) {
                self.kit.alert(self.i18n('pleaseSelectProductOption'));
                return;
            }
            var feedId = self.kit.getCache(self.moduleKey, 'feedId');
            if (self.kit.isBlank(feedId) || feedId == 0) {
                self.kit.alert(self.i18n('pleaseSelectFeedOption'));
                return;
            }
            self.$root.find('.filters div[data-filter-categoryType]:not(.more-filter)').each(function(index, el) {
                var title = $(this).children('.filter-title').text();
                if ($(this).find('.filter-child input[type]:checked').length == 0) {
                    self.kit.alert(self.i18n('pleaseSelect') + title + self.i18n('Option'));
                    valicateFLag = false;
                    return false;
                }
            });
            if (valicateFLag) {
                self.$root.trigger('enterStep2');
            }
        }

        this.adTargetClick = function(e) {
            console.log(e)
        }



        this.i18n = function(key) {
            return I18N.getText('createMaterial', key)
        }

    }
    return me;
});